<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="block">
      <span class="demonstration">三级下拉</span>
      <el-cascader
        v-model="value"
        :options="typeList"
        :props="{label:'typeName',value:'typeId'}"
      ></el-cascader>
    </div>
    <div class="block">
      <span class="demonstration">回显</span>
      <el-cascader
        v-model="value"
        :options="typeList"
        :props="{ expandTrigger: 'hover',label:'typeName',value:'typeId' }"
      ></el-cascader>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="typeList"
      row-key="typeId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="类型名称" align="center" prop="typeName" />
      <el-table-column label="类型排序" align="center" prop="typeSort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="ruleUpdate(scope.row)"
            v-hasPermi="['product:type:edit']"
            v-if="scope.row.children == null"
          >修改规格</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:type:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['product:type:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:type:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级id" prop="parentId">
          <treeselect v-model="form.parentId" :options="typeOptions" :normalizer="normalizer" placeholder="请选择父级id" />
        </el-form-item>
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="类型排序" prop="typeSort">
          <el-input v-model="form.typeSort" placeholder="请输入类型排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改类型对话框 -->
    <el-dialog title="修改类型模板" :visible.sync="ruleOpen" width="500px" append-to-body>
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="80px">
        <el-form-item label="类型">
          {{typeRule.typeName}}
        </el-form-item>
        <el-form-item prop="rultAttr">
          <div v-for="(attr,index) in this.attrValues">
            <el-row>
              <el-col>
                <el-tag
                  :key="attr.key"
                  closable
                  :disable-transitions="false"
                  @close="delAttr(attr.key)">
                  {{attr.key}}
                </el-tag>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-tag
                  :key="val"
                  v-for="val in attr.values"
                  closable
                  :disable-transitions="false"
                  @close="delVal(attr.key, val)">
                  {{val}}
                </el-tag>
                <el-button v-show="attr.addValButStatus" size="mini" @click="addVal(index)">新增</el-button>
                <el-input v-show="attr.addValInpStatus" v-model="attrValue" placeholder="请输入属性" size="mini" style="width: 150px" @blur="valSubmit(attr.key,index)"></el-input>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
      </el-form>
      <el-button v-show="attrButStatus" @click="showFormAttr">添加规格信息</el-button>
      <el-form v-show="attrFormStatus" :inline="true" :model="attrForm" class="demo-form-inline">
        <el-form-item label="规格名称">
          <el-input v-model="attrForm.key" placeholder="请输入规格名称"></el-input>
        </el-form-item>
        <el-form-item label="规格属性">
          <el-input v-model="attrForm.value" placeholder="请输入规格属性"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="attrSumbit">提交</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="ruleSubmitForm">确 定</el-button>
        <el-button @click="ruleCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { getRuleByTypeId, addProductRule, updateProductRule } from "@/api/product/productRule";
  import { listType, getType, delType, addType, updateType } from "@/api/product/type";

  export default {
    name: "Type",
    components: {
      Treeselect
    },
    data() {
      return {
        attrForm: {
          key: '',
          value: ''
        },
        attrFormStatus: false,
        attrButStatus: true,
        addValButStatus: true,
        addValInpStatus: false,
        attrValue: '',
        attrValues: [],
        ruleForm: {},
        typeRule: {},
        ruleOpen: false,
        value: [],
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 类型表格数据
        typeList: [],
        // 类型树选项
        typeOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否展开，默认全部展开
        isExpandAll: true,
        // 重新渲染表格状态
        refreshTable: true,
        // 查询参数
        queryParams: {
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          parentId: [
            { required: true, message: "父级id不能为空", trigger: "blur" }
          ],
          typeName: [
            { required: true, message: "类型名称不能为空", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      // 提交规格属性按钮
      ruleSubmitForm() {
        if (this.ruleForm.productRuleId != null) {
          this.ruleForm.rultAttr = JSON.stringify(this.attrValues);
          updateProductRule(this.ruleForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.ruleOpen = false;
            this.ruleReset();
          });
        } else {
          debugger
          this.ruleForm.rultAttr = JSON.stringify(this.attrValues);
          addProductRule(this.ruleForm).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.ruleOpen = false;
            this.ruleReset();
          });
        }
      },
      /** 属性提交 */
      valSubmit(attrKey,attrIndex){
        if(this.attrValue==''){
          this.$message.warning("属性不可以为空");
          return;
        }
        for(var index in this.attrValues) {
          if (this.attrValues[index].key == attrKey) {
            var values = this.attrValues[index].values;
            var valIndex = values.indexOf(this.attrValue);
            if(valIndex > -1){
              this.$message.warning("属性已经存在");
              return;
            }
            this.attrValues[index].values.push(this.attrValue)
          }
        }
        this.attrValue = '';
        this.attrValues[attrIndex].addValInpStatus=false;
        this.attrValues[attrIndex].addValButStatus=true;
      },
      /** 新增属性 */
      addVal(index){
        this.attrValues[index].addValInpStatus=true;
        this.attrValues[index].addValButStatus=false;
      },
      /** 删除属性 */
      delVal(attrKey, val) {
        var deleteIndex = -1;
        //第一层循环负责找到规格的对象
        for(var index in this.attrValues) {
          if (this.attrValues[index].key == attrKey) {
            //attr 就是规格的对象
            var attr = this.attrValues[index];
            //第二层 循环负责找到 属性所在位置
            for (var valIndex in attr.values) {
              if (attr.values[valIndex] == val) {
                deleteIndex = valIndex;
              }
            }
            //删除属性
            if (deleteIndex > -1) {
              attr.values.splice(deleteIndex, 1)
            }
          }
        }
      },
      /** 商品规格详情 */
      attrSumbit() {
        if(this.attrForm.key=='' || this.attrForm.value =='' ){
          this.$message.warning("规格信息不可以为空")
          return;
        }
        //判断是否有重复规格 如果有重复规格进行添加
        for(var index in this.attrValues){
          if(this.attrValues[index].key == this.attrForm.key){
            if (this.attrValues[index].values.indexOf(this.attrForm.value) > -1){
              this.$message.warning("["+this.attrForm.key+"]规格属性已经含有["+this.attrForm.value+"]")
              return
            }
            this.attrValues[index].values.push(this.attrForm.value)
            // this.attrValues[index].addValInpStatus = true
            this.attrForm = {
              key: '',
              value: ''
            };
            this.showAddAttr()
            return;
          }
        }
        //如果没有重复的创建新的规格对象
        var attr = {
          key: this.attrForm.key,
          values:[this.attrForm.value],
          addValButStatus: true
        }
        this.attrValues.push(attr)
        this.attrForm = {
          key: '',
          value: ''
        };
        this.showAddAttr()
      },
      showFormAttr() {
        this.attrFormStatus = true
        this.attrButStatus = false
      },
      showAddAttr() {
        this.attrFormStatus = false
        this.attrButStatus = true
      },
      /** 删除规格 */
      delAttr(attrValue){
        var attrIndex = -1
        for (var index in this.attrValues) {
          if (this.attrValues[index].key == attrValue) {
            attrIndex = index;
          }
        }
        if (attrIndex !== -1) {
          this.attrValues.splice(attrIndex, 1)
        }
      },
      /** 类型添加规格属性 */
      ruleUpdate(type) {
        this.typeRule = type
        this.ruleOpen = true
        getRuleByTypeId(type.typeId).then(response => {
          if (response.data!=null){
            this.ruleForm = response.data;
            this.ruleForm.typeId = type.typeId
            this.attrValues = JSON.parse(this.ruleForm.rultAttr);
          }else {
            this.ruleReset()
            this.ruleForm.typeId = type.typeId
          }
        })
      },
      //取消按钮
      ruleCancel() {
        this.ruleOpen = false;
        this.ruleReset();
      },
      // 表单重置
      ruleReset() {
        this.ruleForm = {
          productRuleId: null,
          rultAttr: null,
          typeId: null,
          status: "0",
          revision: null,
          createdBy: null,
          createdTime: null,
          updateBy: null,
          updateTime: null
        };
        this.attrValues = [];
        this.resetForm("ruleForm");
      },
      /** 查询类型列表 */
      getList() {
        this.loading = true;
        listType(this.queryParams).then(response => {
          this.typeList = this.handleTree(response.data, "typeId", "parentId");
          this.loading = false;
        });
      },
      /** 转换类型数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.typeId,
          label: node.typeName,
          children: node.children
        };
      },
      /** 查询类型下拉树结构 */
      getTreeselect() {
        listType().then(response => {
          this.typeOptions = [];
          const data = { typeId: 0, typeName: '顶级节点', children: [] };
          data.children = this.handleTree(response.data, "typeId", "parentId");
          this.typeOptions.push(data);
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          typeId: null,
          parentId: null,
          typeName: null,
          typeSort: null,
          isDelete: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        this.getTreeselect();
        if (row != null && row.typeId) {
          this.form.parentId = row.typeId;
        } else {
          this.form.parentId = 0;
        }
        this.open = true;
        this.title = "添加类型";
      },
      /** 展开/折叠操作 */
      toggleExpandAll() {
        this.refreshTable = false;
        this.isExpandAll = !this.isExpandAll;
        this.$nextTick(() => {
          this.refreshTable = true;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getTreeselect();
        if (row != null) {
          this.form.parentId = row.typeId;
        }
        getType(row.typeId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改类型";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.typeId != null) {
              updateType(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addType(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$modal.confirm('是否确认删除类型编号为"' + row.typeId + '"的数据项？').then(function() {
          return delType(row.typeId);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    }
  };
</script>
